// Copyright 2020 morgine.com. All rights reserved.

package handlers

import (
	"gitee.com/tugoer/psys/container"
	"gitee.com/tugoer/psys/models"
	"gitee.com/tugoer/psys/services"
	"github.com/gin-gonic/gin"
)

type getAdvertisementsParam struct {
	Page  int `form:"page" required:""`
	Limit int `form:"limit" required:""`
}

func GetAdvertisements(ctx *gin.Context) {
	p := &getAdvertisementsParam{}
	if err := ctx.Bind(p); err != nil {
		ctx.AbortWithError(500, err)
	} else {
		advertisements, err := container.Advertisements.Get(p.Page, p.Limit)
		if err != nil {
			ctx.AbortWithError(500, err)
		} else {
			err = InitAdvertImageUrl(advertisements)
			if err != nil {
				ctx.AbortWithError(500, err)
			} else {
				ctx.JSON(200, gin.H{"advertisements": advertisements})
			}
		}
	}
}

type saveAdvertisementsParam struct {
	JsonBody string `required:"" desc:"序列化后的 JSON 字符串"`
}

func UpdateAdvertisements(ctx *gin.Context) {
	p := &saveAdvertisementsParam{}
	if err := ctx.Bind(p); err != nil {
		ctx.JSON(200, NewMessage("warning", err.Error()))
	} else {
		err = container.Advertisements.Save(p.JsonBody)
		if err != nil {
			ctx.JSON(200, NewMessage("warning", err.Error()))
		} else {
			ctx.JSON(200, NewMessage("success", "已保存"))
		}
	}
}

type Message struct {
	Type    string `json:"type"`
	Content string `json:"content"`
}

func NewMessage(kind, message string) gin.H {
	return gin.H{
		"message": Message{
			Type:    kind,
			Content: message,
		},
	}
}

func InitAdvertImageUrl(ads []*models.Advertisement) error {
	var err error
	for _, ad := range ads {
		ad.ImgUrl, err = services.ImgStore.GetServeUrl(ad.Img)
		if err != nil {
			return err
		}
	}
	return nil
}
